package com.mashibing.filter;

import com.mashibing.internalcommon.constant.TokenConstants;
import com.mashibing.internalcommon.dto.TokenResult;
import com.mashibing.internalcommon.util.JwtUtils;
import com.mashibing.internalcommon.util.RedisPrefixUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class AuthFilter implements GlobalFilter {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private PathInterceptorConfig pathInterceptorConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        List<String> authList = pathInterceptorConfig.getExcludePathPatterns();

        RequestPath path = exchange.getRequest().getPath();

        System.out.println("请求路径为：" + path);

        if (!authList.contains(path.toString())) {
            boolean result = true;

            String headerToken = exchange.getRequest().getHeaders().getFirst("Authorization");

            // 解析token
            TokenResult jwtToken = JwtUtils.checkToken(headerToken);

            if (jwtToken == null) {
                result = false;
            }

            // 解析成功，与redis中的token对比校验
            if (jwtToken != null) {
                // 与redis中token对比
                String redisTokenKey = RedisPrefixUtils.generatorTokenKey(jwtToken.getPhone(), jwtToken.getIdentity(), TokenConstants.ACCESS_TOKEN_TYPE);
                String token = redisTemplate.opsForValue().get(redisTokenKey);
                if (StringUtils.isBlank(headerToken) || !headerToken.equals(token)) {
                    result = false;
                }
            }

            if (!result) {
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

        }

        return chain.filter(exchange);
    }
}
